const bcrypt = require('bcryptjs')
const { Sequelize, Model } = require('sequelize')
const {AuthFailed } = require('../../core/http-exception')

const { sequelize } = require('../../core/db')

// 定义模型
class User extends Model {

    static async verifyEmailPassword(email, plainPassword) {
        // 用户是否存在
        const user = await User.findOne({
            where: {
                email
            }
        })

        if (!user) {
            throw new AuthFailed("用户不存在",10001)
        }

        // 对比用户密码
        const correct = bcrypt.compareSync(plainPassword, user.password)
        if(!correct){
            throw new AuthFailed("密码错误",10002)
        }

        return user
    }

    // 查询 微信授权的 openid
    static async getUserByOpenId(openid){
        return await User.findOne({
            where:{
                openid
            }
        })
    }

    // 新增用户授权的openid
    static async registerByOpenId(openid){
        return await User.create({
            openid
        })
    }


}

User.init({
    // 主键 id
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
    },
    nickname: Sequelize.STRING,
    email: {
        type: Sequelize.STRING,
        unique: true
    },
    password: {
        type: Sequelize.STRING,
        set(val) {
            const salt = bcrypt.genSaltSync(10); // 10 是计算密码的成本 
            const pwd = bcrypt.hashSync(val, salt);
            // 观察的 字段名 password  值
            this.setDataValue('password', pwd)
        }
    },
    openid: {
        type: Sequelize.STRING(64),
        unique: true
    }
}, { sequelize: sequelize, tableName: 'user' })

module.exports = {
    User
}